<!DOCTYPE HTML>
<html lang="en">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="前端面试手撕JS代码系列（五）, Casey Lu&#39;s Blog">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>前端面试手撕JS代码系列（五） | Casey Lu&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/medias/maozhao.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 4.2.0"><link rel="alternate" href="/atom.xml" title="Casey Lu's Blog" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Casey Lu's Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>Index</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>Tags</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>Categories</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>Archives</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>About</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="Search" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Casey Lu's Blog</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			Index
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			Tags
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			Categories
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			Archives
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			About
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('嘻嘻嘻，访问本文章需要密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误哦~');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/articleimages/13.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">前端面试手撕JS代码系列（五）</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Javascript/">
                                <span class="chip bg-color">Javascript</span>
                            </a>
                        
                            <a href="/tags/CSS/">
                                <span class="chip bg-color">CSS</span>
                            </a>
                        
                            <a href="/tags/%E7%AE%97%E6%B3%95/">
                                <span class="chip bg-color">算法</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E7%AC%94%E8%AF%95%E9%9D%A2%E8%AF%95/" class="post-category">
                                笔试面试
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>Publish Date:&nbsp;&nbsp;
                    2020-03-30
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>Word Count:&nbsp;&nbsp;
                    2.6k
                </div>
                

                

                
            </div>

        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>算法对于前后端开发都非常重要，即便在不笔试的情况下，面试官还是喜欢检验我们的算法功底，以及通过让你说程序的运行结果考察我们对知识点的掌握程度，这样就会立刻看出你的情况，整理了一下最近在面试中遇到的手写代码题目，包含前端基础题和算法题<img class="emoji" draggable="false" alt="📝" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4dd.png"/>。</p>
<p><strong>考点总结：</strong> 排序、 树的遍历、随机生成、this指向（bind、call、apply）、异步、Promise、深拷贝、事件流、防抖和节流</p>
<p><strong>算法题</strong></p>
<h2 id="数组两元素之和">数组两元素之和</h2>
<p>场景： 蚂蚁金服二面<br>
考点： 排序、双指针</p>
<p>找出一个升序数组中，和为sum的两个元素，要求时间复杂度小于O(n*n)<br>
比较简单，<code>left + right &gt; sum , right -- ; left + right &lt; sum, left ++ </code></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var findIndex = function(arr, sum){
  let i = 0,j = arr.length-1
  while(i !== j){
    let tmpSum = arr[i] + arr[j]
    if(tmpSum < sum){
      i++
    }else if(tmpSum > sum){
      j--
    }else{
      return arr[i],arr[j]
    }
  }
}
</code></pre>
<p>延伸扩展——找出一个数组中两个和为targetNumber的元素的索引[i,j]，数组为无序数组（美团二面）。<br>
这个开始我有点头大，因为输出的是索引，后来面试官真的很好，一直耐心引导我，我的思维便不再受排序牵制，然后利用Map解决了这个问题，但不同的是由于map中的has方法只能针对key进行判断（例如：<code>map.has('name')</code>），所以我们要一反常规，把数值arr[i]作为key，把索引index作为value，这样就可不使用Array.indexOf遍历就能获取索引，同时但又能查询数组中是否包含某数值。</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var findIndex = function(arr, target){
  var map = new Map()
  // 初始化Map
  arr.forEach((item,index) =>{
    map.set(item,index) // item作为key,index作为value
  })
  // 遍历查询
  arr.forEach((item,i)=>{
    let tmp = target-item
    if(map.has(tmp)){ // 判断Map中是否有恰好合适的值
      return [i,map.get(tmp)]
    }
  })
}
</code></pre>
<h2 id="数组的去重">数组的去重</h2>
<p>场景： 蚂蚁金服一面<br>
考点： 数组的操作，连带考察Array的方法</p>
<p>这个在之前 <em><a href="https://caseylu.gitee.io/2020/03/06/5-javascript-bi-shi-shua-ti-xiao-jie-yi/#toc-heading-2">JS刷题小结（一）</a></em> 中有讲，不再重复声明，要考虑是否改变原数组，以及不同时间和空间复杂度的限制情况</p>
<p>除了使用排序和indexOf,在此补充几种去重：</p>
<ol>
<li><strong>利用Object属性不同去重</strong></li>
</ol>
<pre class=" language-language-javascript"><code class="language-language-javascript">var removeDuplicates = function(arr){
  let obj = {}
  let newArray = []
  arr.forEach((item) =>{
    if(!obj[item]){
      obj[item] = 1
      newArray.push(item)
    }
  })
  return newArray
}
</code></pre>
<ol start="2">
<li><strong>splice删除元素,改变原数组</strong></li>
</ol>
<pre class=" language-language-javascript"><code class="language-language-javascript">var removeDuplicates = function(arr){
  let len = arr.length
  for(let i = 0; i < len; i++){
    for(let j = i+1; j < len; j++){
      if(arr[i] === arr[j]){
        arr.splice(j,1)
        len --
        j --
      }
    }
  }
  return arr
}
</code></pre>
<ol start="3">
<li><strong>利用ES6的Set特性——成员唯一性</strong></li>
</ol>
<pre class=" language-language-javascript"><code class="language-language-javascript">var removeDuplicates = function(arr){
  return Array.from(new Set(arr))
}
</code></pre>
<h2 id="js洗牌函数">js洗牌函数</h2>
<p>场景： 蚂蚁金服二面</p>
<p>你来设计一个算法，打乱一副扑克牌[0,53]的顺序<br>
<strong>思路：</strong> 在不修改原数组的情况下，打乱新的顺序，随机生成索引和当前互换</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var shuffleCards = function(arr){
  let arrCopy = arr.slice()
  for(let i = 0; i < arr.length; i++){
    let j = getRandom(0,i) // 生成随机索引
    let temp = arrCopy[i]
    arrCopy[i] = arrCopy[j]
    arrCopy[j] = temp
  }
  return arrCopy
}
//随机函数（min,max）之间的随机整数
function getRandom(min, max){
  return Math.floor(Math.random()*(max-min+1) + min)
}
</code></pre>
<h2 id="爬梯子问题">爬梯子问题</h2>
<p>场景： 字节跳动一面<br>
考点： leetcode青蛙跳台阶，递归及非递归实现</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">// 递归实现
var jumpStage = function(n){
  if(n <= 2)  return n
  return jumpStage(n-1) + jumpStage(n-2)
}
// 非递归实现
var jumpStage = function(n){
  if(n <= 2)  return n
  let pre = 1
  let next = 2
  for(let i = 3; i <= n; i++){
    let tmp = next
    next += pre
    pre = tmp
  }
  return next
}
</code></pre>
<h2 id="生成随机数组">生成随机数组</h2>
<p>场景： 字节跳动二面<br>
考察：随机数的生成、去重</p>
<p>请写出一个可以生成整形随机数数组(内部元素不重复)的函数，并可以根据参数设置随机数生成的范围和数量，例如：函数madeRandomList(a, b, c)，可以生成 [a, b] 范围内，长度为 c 的随机数数组</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var madeRandomList = function(a,b,c){
  let randomList = []
  let cnt = 0 // 生成的随机数的个数
  while(cnt < c){
    let r = Math.floor(Math.random()*(b-a+1) + a)
    if(randomList.indexOf(r) === -1){ // 未生成过这个随机数字
      randomList.push(r)
      cnt ++
    }
  }
  return randomList
}
</code></pre>
<h2 id="求和函数">求和函数</h2>
<p>场景： 腾讯WXG一面<br>
考点：柯里化、arguments、toString()<br>
题目：实现sum函数，结果如下</p>
<blockquote>
<p>sum().result = 0<br>
sum(2,3).result = 5<br>
sum(1,2)(3).result = 6<br>
sum(1,2)(3,4).result = 10<br>
sum(1,2)(3,4)(5).result = 15</p>
</blockquote>
<p>之前没有研究过柯里化，所以手撕代码这道题直接铺gai，不得不说鹅厂WXG的题真的是有些难度的，从来没想过会败给sum函数，原因还是自己没有深入了解吧<br>
<img src="https://img-blog.csdnimg.cn/20200329174654164.png" alt="为啥不学柯里化，为啥不好好研究sum"><br>
<strong>柯里化</strong></p>
<blockquote>
<p>柯里化（Currying）：把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数，并且返回接受余下的参数且返回结果的新函数的技术</p>
</blockquote>
<p>一般情况下，简单的两个参数的例子可以直接写：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function curry(sum, a){
  return function(b){
    return sum(a+b)
  }
}
</code></pre>
<p><img class="emoji" draggable="false" alt="💭" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4ad.png"/>但如果参数增多呢?总不能无限嵌套下去吧… …于是，我们可以使用闭包思想改造一下！</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function curry(fn, ...args){
  var length = fn.length // fn中的参数数量
  return function(...nextArgs){
    var allArgs = [...args,...nextArgs] // 收集参数
    if(allArgs.length >= length)
      return fn.apply(null,allArgs) // 参数足够调用原参数
    return curry(fn, ...allArgs) // 不够参数，继续递归调用
  }
}
var currySum = curry(sum)
currySum(1,2,3)(4)(5)
</code></pre>
<p>把上一批参数和下一批参数结合在一起，然后返回一个函数，继续相同的模式。<br>
<img class="emoji" draggable="false" alt="💭" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4ad.png"/>上述情况下参数是固定的,而在真实的需求中，我们参数的数量往往是未知且不固定的。我们可以把上面根据参数数量结束的条件删减掉，返回一个函数</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function curry(fn, ...args){
  return function(...nextArgs){
    var allArgs = [...args, ...nextArgs]
    return curry(fn, ...allArgs)
  }
}
</code></pre>
<p>最后修改为符合题目要求的代码，还需要添加result获取值</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function sum(...args){
  var f = function(...nextArgs){
    var allArgs = [...args, ...nextArgs]
    return sum(...allArgs)
  }
  // 定义sum值
  f.res = args.length !== 0 ? args.reduce((a,b) => a+b) : 0
  return f
}
console.log(sum(1,2,3)(4,5)(6).result)
</code></pre>
<p>好啦，小功告成！<img class="emoji" draggable="false" alt="😎" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f60e.png"/></p>
<h2 id="连续子数组">连续子数组</h2>
<p>场景：腾讯WXG一面<br>
考点：数组遍历<br>
题目：寻找和最大的连续子数组，输出最大和</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">var findMaxSum = function(nums){
  if(nums.length <= 0)  return 0
  var tempSum = nums[0]
  var maxSum = nums[0]
  num.forEach((item) = >{
    if(tempSum < 0){ // 之前的和为负数，弃掉
      tempSum = nums[i]
    }else{ // 继续累加
      tempSum += nums[i] 
    }
    // 更新最大的sum
    maxSum = Math.max(tempSum, maxSum)
  })
  return maxSum
}
</code></pre>
<p><strong>前端技术的手写题：</strong></p>
<h2 id="手写事件监听">手写事件监听</h2>
<p>场景： 字节跳动一面<br>
考点： DOM操作，事件流<br>
相关知识：<br>
JS事件流——描述的是从页面中接收事件的顺序<br>
三个阶段：事件捕获阶段、处于目标阶段、事件冒泡阶段<br>
如何实现先冒泡后监听? 对同一个时间监听捕获和冒泡，分别处理响应的函数，监听到捕获时先暂缓执行，直到冒泡事件被捕获后再执行捕获。</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">const div1 = document.getElementById('div1')
div1.addEventListener('click', e =>{
  e.preventDefault() // 阻止默认的行为
  console.log('监听成功')
})
</code></pre>
<p><code>addEventListener</code>是W3C DOM规范中提供的事件监听器方法，<code>element.addEventListener(event, function, useCapture)</code></p>
<blockquote>
<p>三个参数(String, fn, boolean)，第三个是可选参数<br>
<code>useCapture：false</code>是默认值，表示事件句柄在冒泡阶段执行；<code>true</code>则表示在捕获阶段执行。<br>
<code>removeEventListener</code>使用方法相同，IE8及以下不支持，解决：可以使用<code>detachEvent()</code>移除<code>attachEvent()</code></p>
</blockquote>
<p><img class="emoji" draggable="false" alt="❓" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/2753.png"/> 使用<code>addEventListener</code>和直接元素上写事件<code>attachEvent</code>有区别吗？</p>
<ul>
<li><code>addEventListner</code>能够添加多个事件绑定，按照顺序执行；<code>attachEvent</code>添加事件后不能绑定多个事件，后面的绑定会覆盖前面的</li>
<li><code>addEventListner</code>有可选参数<code>useCapture</code>支持在事件捕获阶段（true）或者冒泡阶段（false）绑定；<code>attachEvent</code>只能在时间冒泡阶段捕获</li>
<li><code>addEventListner</code>绑定之后还可以使用<code>removeEventListner</code>取消；而普通方式绑定事件之后，不能取消</li>
<li><code>addEventListner</code>不支持低版本的IE（<code>attachEvent</code>支持IE）；</li>
<li><code>attachEvent</code>的type使用&quot;on&quot;前缀，语法<code>attachEvent(type, callback)</code></li>
</ul>
<p>写一个通用的事件监听函数</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">// 通用的事件绑定函数(既能支持普通，也能支持事件代理)
function bindEvent(element, type, selector, fn){
  if(fn === null){
    // 三个参数的情况下，说明没有设置选择器
    fn = selector
    selector = null
  }
  element.addEventListener(type, e =>{
    const target = e.target
    if(target.matches(selector)){ 
    // 检查target触发事件的节点，是否与我们传入的selector匹配
      fn.call(target, e)
    }else{
      fn(e)
    }
  })
}
// 示例1：只给div1中的a标签绑定事件，其他不管
var div1 = document.getElementById('div1')
bindEvent(div1, 'click', 'a', function(e){
  e.preventDefault()
  console.log(this.innerHTML)
})
// 示例2：只某个id为p1的<p>标签绑定事件
bindEvent(p1, 'click', function(e){
  console.log('You have clicked this p label')
})
</code></pre>
<h2 id="手写call、apply和bind函数">手写call、apply和bind函数</h2>
<p>场景:  字节跳动一面<br>
考点：this指向</p>
<p>先来思考<img class="emoji" draggable="false" alt="💭" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4ad.png"/>：<img class="emoji" draggable="false" alt="1️⃣" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/31-20e3.png"/> call可以被所有方法调用，所以必然定义在Function的原型上；<img class="emoji" draggable="false" alt="2️⃣" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/32-20e3.png"/> 绑定函数被调用时，只传入第二个参数及之后的参数 <img class="emoji" draggable="false" alt="3️⃣" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/33-20e3.png"/> 显示绑定this<img class="emoji" draggable="false" alt="❓" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/2753.png"/>如果调用者函数，被某一个对象所拥有，那么该函数在调用时，内部的this指向该对象。</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">Function.prototype._call = function(ctx) {
}
fn.call()
fn._call()
</code></pre>
<pre class=" language-language-javascript"><code class="language-language-javascript">Function.prototype.call = function(context){
  const cxt = context || window
  // 将当前被调用的方法定义在cxt.fn上，（以对象调用的形式绑定this）
  cxt.fn = this
  // 获取实参
  const args = Array.from(arguments).slice(1)
  // 以对象调用的形式调用fn,此时的this指向cxt，也是传入的需要绑定的this指向
  const res = arguments.length > 1 ? cxt.fn(...args): cxt.fn()
  // 删除这个方法，避免对传入对象造成污染
  delete cxt.fn
  return res
}
</code></pre>
<p>延伸扩展——<strong>手写apply函数</strong></p>
<p>除了从参数处理之外，基本和call相同</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">Function.prototype.apply = function(context){
  const cxt = context || window
  cxt.fn = this
  const res = arguments[1] ? cxt.fn(...arguments[1]) : cxt.fn()
  delete cxt.fn
  return res
}
</code></pre>
<p>延伸扩展——<strong>手写bind函数</strong></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">Function.prototype._bind = function(){
  // 无法直接获取参数，利用arguments，将参数解析为数组
  const args = Array.propotype.slice.call(arguments)  
  const _this = args.shift()  // 获取this（数组第一项），剩余的是传递参数
  const self = this  // fn1._bind(...)中的fn1

  return function(){     
    return self.apply(_this, args)  // 执行原函数，返回结果
  }
}
// 示例:验证bind与原生的效果相同
const fn2 = fn1._bind({x:100,y:200},1,23,4)
const res = fn2()
console.log(res)
const fn3 = fn1.bind({x:100,y:200},1,23,4)
const res1 = fn3()
console.log(res1)
</code></pre>
<p><strong>call、apply、bind的区别与联系：</strong></p>
<ul>
<li>三者都是改变this指向的函数，param1：this要指向的对象</li>
<li>call 和 apply 借用其他对象方法，调用立即执行；bind会返回新的函数，不会立即调用</li>
<li>apply与call的区别是apply第二个是参数组，call则是arg1,arg2,arg3这种形式</li>
<li>在确定的参数下，还是最好用call，它的效率会更高，但是在函数的延展性上使用apply更好</li>
</ul>
<h2 id="手写深拷贝">手写深拷贝</h2>
<p>场景： 字节跳动一面<br>
考点： 简单、复杂数据类型</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function deepClone(obj){
  var newObj = obj instanceof Array?[]:{}
  for(var item in obj){
    var temp = typeof obj[item] === 'Object' ? deepClone(obj[item]): obj[item]
    newObj[item] = temp 
  }
  return newObj
}
</code></pre>
<p><strong>浅拷贝 vs 深拷贝</strong><br>
浅拷贝智能拷贝一级元素，不能拷贝子元素，相当于仅仅是复制一份引用<br>
深拷贝，则会复制变量值，对于非基本类型的变量，则递归到基本类型的变量之后，再复制。</p>
<h2 id="数据类型判断">数据类型判断</h2>
<p>场景： 字节跳动一面<br>
考点：<code>typeOf</code>，<code>instance of</code>，<code>Object</code></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">console.log(typeOf []) // Object
console.log( [] instanceOf Object ) //true 
console.log( [] instanceOf Array) //true 
</code></pre>
<p><code>typeOf</code>不能用于判断Array类型，返回的总是Object,无法判断是对象还是数组；因此涉及到对Array的判断肯定使用<code>instanceOf</code></p>
<h2 id="手写debounce和throttle函数">手写debounce和throttle函数</h2>
<p>场景： 字节跳动一面<br>
考点： 节流、防抖<br>
题目：写一下项目中你写的节流函数（cc的项目是Vue）<br>
防抖节流就是使用定时器实现我们的目的，防抖是持续触发一段时间后触发，节流是每隔一段时间触发</p>
<p><strong>Vue项目中的防抖和节流</strong>（如果多处使用，放在public.js）</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">// 节流函数
function throttle(fn, delay = 200){
  let timer = null
  return function(){
    if(timer){
      return
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments)
      timer = null
    },delay)
  }
}
// 示例
div.addEventListener('drag', throttle((e)=>{
  console.log(e.offsetX,e.offsetY)
},100))

// 防抖函数
function debounce(fn, delay = 200){ 
  let timer = null
  return function(){     
    if(timer){
      clearTimeout(timer)
    }
    timer = setTimeout(function(){
      timer = null
      fn.apply(this,arguments)
    }, delay)
  }
}
// 示例
input = document.getElementById('input1')
input.addEventListener('keyup', debounce(() => {
  cosole.log(input.value)
}),500)
</code></pre>
<h2 id="手写闭包">手写闭包</h2>
<p>考点：闭包、作用域<br>
例题：<strong>手写一个闭包实现隐藏数据的效果</strong></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function createCache() {
  const data = {}
  return {
    set: function(key, value){
      data[key] = value
    }
    get: function(key){
      return data[key]
    }
  }
}
// 定义闭包对象，实现对闭包内部变量的隐藏，只能通过get和set访问
const c = createCache()
c.set('age', 24)
console.log('age:' + c.get('age'))
</code></pre>
<p>闭包的诸多应用：模仿块级作用域；保存外部函数的变量；封装私有变量；隐藏数据</p>
<h2 id="var-和-let">var 和 let</h2>
<p>场景： 蚂蚁金服一面、字节跳动一面<br>
考点： let, var的区别，变量提升的理解</p>
<p>以下程序的运行结果是什么？为什么？</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">for(let i = 0; i < 5; i++){
  let i = 3
  console.log(i)
}
</code></pre>
<p>output:</p>
<pre class=" language-language-bash"><code class="language-language-bash">3
3
3
3
3
</code></pre>
<pre class=" language-language-javascript"><code class="language-language-javascript">for(var i = 0; i < 5; i++){
  let i = 3  
  console.log(i)  
}
</code></pre>
<p>同上</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">for(var i = 0; i < 5; i++){
  var i = 3
  console.log(i)
}
</code></pre>
<p>output : 无数个3</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">console.log(a)
var a = 5
</code></pre>
<p>output:  <code>undefined</code></p>
<p><strong>知识回忆：</strong><br>
var不可以重复声明，var可以变量提升，作用域是全局，但只是变量声明的提升，赋值不会提升<br>
let允许重复声明，let不会变量提升，只在声明后的块状作用域内有效</p>
<h2 id="setTimeout函数">setTimeout函数</h2>
<p>场景：字节跳动一、二面<br>
考点： 观察程序结果、谈对异步的理解</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">for(var i = 0； i < 5; i++){
  setTimeout(function(){
    console.log(i)
  },1000)
}
</code></pre>
<p>结果是：  5 5 5 5 5<br>
如果想输出： 0 1 2 3 4 , 将var改为let,考察变量的作用域</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">setTimeout(function(){
  console.log(5)
},1)
}
</code></pre>
<p><code>setTimeout</code>的时间设置小于4ms的时候相当于没有延迟,不起作用</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">console.log('script start')
let promise1 = new Promise(function (resolve) {
  console.log('promise1')
  resolve()
  console.log('promise1 end')
  }).then(function () {
    console.log('promise2')}
  )
setTimeout(function(){
  console.log('settimeout')
}, 1000)
console.log('script end')
</code></pre>
<p>result:</p>
<pre class=" language-language-bash"><code class="language-language-bash">script start
promise1
promise1 end
script end
promise2
settimeout
</code></pre>
<p>JS是单线程语言，同步会阻塞进程，异步则不会</p>
<h2 id="DOM树的遍历">DOM树的遍历</h2>
<p>场景：字节跳动二面<br>
考点：DOM、DFS<br>
题目描述：打印DFS遍历的DOM数序列，<br>
Output:  [“div”, “span”, “a”, “div”, “a”, “span”, “p”]<br>
<img src="https://img-blog.csdnimg.cn/20200325212300376.png" alt="DOM树"><br>
<strong>DOM的属性和操作：</strong></p>
<ul>
<li>新增/插入节点  <code>createElement('p')</code> 、<code>appendChild(p1)</code></li>
<li>获取子节点列表<code>childNodes</code>，获取父元素 <code>parentNode</code></li>
<li>删除子节点, <code>removeChild(node)</code></li>
</ul>
<p><strong>DOM性能的优化：</strong></p>
<ul>
<li>避免频繁地进行DO操作</li>
<li>对DOM的查询结果做缓存</li>
<li>将频繁的操作改为一次性操作</li>
</ul>
<p><strong>DFS遍历DOM树（递归&amp;非递归）</strong></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">// DFS遍历,递归
var res = []
var dfsDOM = function(node){
  if(node){
    res.push(node)
    let children = node.childrenNodes
    children.forEach((item)=>{
      dfsDOM(item)
    })
  }
}
// DFS遍历，非递归(栈)
var dfsDOM = function(node){
  var res = [] // 已遍历的节点
  if(node){
    var nodesList = [] // 待遍历的节点栈
    nodesList.push(node)
    while(nodesList.length > 0){
      let curNode = nodesList.pop() //弹出栈顶的元素，放入res,表示遍历过
      res.push(curNode)
      let children = curNode.childrenNodes
      // 逆序的把当前节点的孩子节点都放入栈中（保证弹出时顺序正确）
      for(let i = children.length-1; i >= 0; i--){
        nodeList.push(childen[i])
      }
    }
  }
  return res
}
</code></pre>
<p><strong>BFS遍历DOM树（递归&amp;非递归）</strong></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">// BFS遍历,递归
var res = []
var bfsDOM = function(node){
  if(res.indexOf(node)===-1){
    res.push(node)
  }
  let children = node.childrenNodes
  children.forEach((item) => {
    if(item){
      res.push(item) // 存储当前节点的所有非空子节点，放入res表示遍历过
    }
  })
  // 继续对所有子节点的子节点进行递归遍历
  children.forEach((item) =>{
    bfsDOM(item)
  })
  return res
}
// BFS遍历，非递归（队列）
var bfsDOM = function(node){
  var res = [] // 已遍历
  var nodeList = [] // 待遍历
  nodeList.push(node)
  while(nodeList.length > 0){
    var curNode = nodeList.shift(0)
    res.push(curNode)
    let children = curNode.childrenNodes
    children.forEach((item) => {
      nodeList.push(item)
    })
  }
  return res
}
</code></pre>
<p>延伸扩展——<strong>如何高效的插入多个DOM节点，考虑性能</strong><br>
例题： <strong>在name为list的div下面插入10个 li 列表项</strong><br>
思路： 逐个频繁插入是损耗DOM性能的，于是利用上面的第三点<img class="emoji" draggable="false" alt="👉" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f449.png"/> 将频繁的操作改为一次性的操作，先创建文档片段，作为一个临时的存储空间，创建多个li并放入，最后整体插入到DOM树中，这样就只需要执行一次DOM操作了。</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">const listDiv = document.getElementById('list')
// 创建文档片段，此时未插入dom树
const frag = document.createDocumentFragment()
// 执行插入
for(let i = 1; i <= 10; i++){
  const li = document.createElement('li')
  li.innerHTML = `List Item-${i}`
  frag.appendChild(li)
}
// 都加载完成之后，再将整个插入到DOM树
listDiv.appendChild(frag)
</code></pre>
<h2 id="手写链式调用">手写链式调用</h2>
<p>场景： 美团二面<br>
考点： 方法链<br>
题目： 设计一个累加功能的方法链的封装，可以无限累加，并且可以获取累加的值</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function continueAdd(){
  var a = 3
}
continueAdd.prototype.add = function(){
  a += arguments[0]
  return this
}
continueAss.prototype.get = function(){
  return a
}
// 示例
let n = new numberAdd()
console.log(n.add(5).add(8).add(1))
console.log(n.get())
</code></pre>
<h2 id="原型与原型链">原型与原型链</h2>
<p>场景： 腾讯WXG一面<br>
考点： OOP，原型及原型链<code>__proto__</code><br>
题目：实现一个 <code>GoodMan</code>类， 要求如下</p>
<p>1）<code>GoodMan(&quot;Tom&quot;)</code></p>
<p>输出: I am Tom</p>
<p>2）<code>GoodMan(&quot;Tom&quot;).rest(10).learn(&quot;computer&quot;)</code><br>
输出:</p>
<blockquote>
<p>I am Tom<br>
//等待10秒<br>
Start learning after 10 seconds<br>
Learning computer</p>
</blockquote>
<p>3）<code>GoodMan(&quot;Tom&quot;).restFirst(5).learn(&quot;Chinese&quot;)</code><br>
输出:</p>
<blockquote>
<p>//等待5秒<br>
Start learning after 5 seconds<br>
I am Tom<br>
Learning Chinese</p>
</blockquote>
<p>具体实现如下：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">// 构建GoodMan类
function GoodMan(name){
  var _this = {}
  _this.__proto__ = arguments.callee.prptotype
  _this.name = `I am ${name}`
  setTimeout(_this.setTimePrint.bind(_this))
  return _this
}
GoodMan.prototype.learn = function(subject){
  this._learn = subject
  return this
}
// 在学习学科之前的休息
Goodman.prptotype.rest = function(cnt){
  this._rest = cnt
  return this
}
// 自我介绍前的休息
GoodMan.prototype.restFirst = function(cnt){
  this._rest = 0
  this._restFirst = cnt
  return this
}
// 自定义restFirst执行时的延迟函数
GoodMan.prototype.delay = function(){
  const d  = new Date()
  const n = this._restFirst*1000
  for(let i = 0; i < d; i++){
    if(new Date() - d > n){
      return false
    }
  }
}
// 两个rest函数与其他操作的逻辑实现，输出顺序的控制
GoodMan.prototype.setTimePrint = function(){
  var { name, _learn, _rest, _restFirst } = this
  var cnt = _rest || _restFirst
  
  if(_restFirst !== undefined){
    this.delay()
  }else{
    console.log(name) // 自我介绍
  }
  
  if(cnt){
    // 延迟后执行的内容们
    console.log(`Start learning after ${cnt} seconds`)
    setTimeout(function(){
      if(_restFirst !== undefined){
        console.log(name)
      }
      if(_learn){
        console.log(`Learning ${_learn}`)
      }
    }, _rest*1000)
  }
}
</code></pre>
<h2 id="编写查询函数">编写查询函数</h2>
<blockquote>
<p>已知有两个接口[GET] /api/user/get?id= 根据 id 获取用户的年级和班级</p>
<ul>
<li>传入用户 id</li>
<li>返回 json body: { id, name, grade, class }</li>
</ul>
<p>[GET] /api/user/search?query=根据查询内容返回符合条件的用户列表</p>
<ul>
<li>传入字符串 query</li>
<li>返回 json body: [{ id, name },…]</li>
</ul>
</blockquote>
<p>题目：要求编写一个查询函数，根据传入字符串 query 来返回满足条件的用户的详情列表即：返回 json body: [{ id,name, grade, class }, …]</p>
<p><strong>vegetable-chicken cc 总结：</strong></p>
<p>算法题一般都来源于我们的日常做题，而其他前端基础题虽然考察形式千变万化，但实际上都是知识点的形式迁移，只要掌握了知识点及相关原理，观察和分析程序的运行结果便不在话下。</p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        Author:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io" rel="external nofollow noreferrer">Casey Lu</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        Link:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io/2020/03/30/21-qian-duan-mian-shi-shou-si-js-dai-ma-xiao-jie-wu/">https://caseylu.gitee.io/2020/03/30/21-qian-duan-mian-shi-shou-si-js-dai-ma-xiao-jie-wu/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        Reprint policy:
                    </i>
                </span>
                <span class="reprint-info">
                    All articles in this blog are used except for special statements
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    reprint polocy. If reproduced, please indicate source
                    <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>Copied successfully, please follow the reprint policy of this article</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">more</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Javascript/">
                                    <span class="chip bg-color">Javascript</span>
                                </a>
                            
                                <a href="/tags/CSS/">
                                    <span class="chip bg-color">CSS</span>
                                </a>
                            
                                <a href="/tags/%E7%AE%97%E6%B3%95/">
                                    <span class="chip bg-color">算法</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">谢谢大佬的小鱼干，喵~</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'b739596984975414aa79',
        clientSecret: 'c5792bc3376f951910111f232176fbadfa919286',
        repo: 'L0ittle.github.io',
        owner: 'L0ittle',
        admin: "L0ittle",
        id: '2020-03-30T21-36-24',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;Previous</div>
            <div class="card">
                <a href="/2020/03/31/22-yang-chun-san-yue-de-bi-xia-liu-shui/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/2.jpg" class="responsive-img" alt="三月的笔下流水">
                        
                        <span class="card-title">三月的笔下流水</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            2020年3月份，我想这是我读研以来最辛苦的一个月份，习惯了接近二十年校园生活的襁褓，面对求职这个接下来人生的重要的转折阶段，二次逆风成长。
挫折乃成长良药
这个世界上一路顺畅通关打怪的人绝对不占据多数，除非实力超群或者幸运满分。之前遇到的
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-31
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E4%BA%BA%E7%94%9F%E6%9D%82%E8%B0%88/" class="post-category">
                                    人生杂谈
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Life/">
                        <span class="chip bg-color">Life</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                Next&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/03/28/20-css-zhong-chang-jian-de-bu-ju-fang-shi/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/32.jpg" class="responsive-img" alt="CSS中常见的布局方式">
                        
                        <span class="card-title">CSS中常见的布局方式</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            面试被问到了三列布局的实现，只回答出来了float、Position
三列布局
实现三列布局通常是两列定宽，一列自适应，在这里主要讲两侧定宽，中间自适应的布局：
浮动实现三列布局

float  + margin
使用float浮动实现，脱
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-03-28
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" class="post-category">
                                    技术分享
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/CSS/">
                        <span class="chip bg-color">CSS</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('100')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + 'From: Casey Lu&#39;s Blog<br />'
            + 'Author: Casey Lu<br />'
            + 'Link: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;TOC</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="4892766072"
                   fixed='true'
                   autoplay='false'
                   theme:='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2020</span>
            <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">63.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/L0ittle" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:caseylu119@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1351238945" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1351238945" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;Search</span>
            <input type="search" id="searchInput" name="s" placeholder="Please enter a search keyword"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
